#!coding:utf-8
from django.db import transaction
from rest_framework import status
from cvirt.manager.models import Thinclient, User, Instance
from cvirt.manager.views import NamedAPIViewMixIn
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from cvirt.common import translate as _,utils
from cvirt.tasks import client_start_vm


class Client(NamedAPIViewMixIn,GenericAPIView):
    '''
    no need authentication
    '''
    permission_classes = ()
    authentication_classes = ()

    def get_client_ip(self,request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def register(self, request, *args, **kwargs):
        client_name = self.get_params('client_name')
        client_ip = self.get_params('client_ip')
        client_mac = self.get_params('client_mac')
        client_os = self.get_params('client_os')
        client_cpu = self.get_params('client_cpu')
        client_memory = self.get_params('client_memory')

        for k,v in locals().items():
            if k.startswith('client') and not v:
                return Response(_("%s不能为空" % k),status=status.HTTP_400_BAD_REQUEST)

        client,iscreated = Thinclient.objects.get_or_create(name=client_name,ip=client_ip,mac = client_mac,os=client_os,cpu=client_cpu,
                                  mem=client_memory)

        return Response(dict(id=client.id))

    def login(self,req,*args,**kwargs):
        username = self.get_params('username')
        passwd = self.get_params('password')
        if username and passwd:
            user = User.objects.first(username=username,password=passwd)
            if user:
                result = dict(userid=user.id,username=username,status=user.status,vms=[])
                for vm in user.instance_set.all():
                    if vm.graphics_type == 'spice':
                        result['vms'].append(dict(id=vm.id,status=vm.status,name=vm.name,
                                                  host=vm.host.ip,password=vm.remote_password,
                                                  port=5900+int(vm.id),os_type=vm.os_type))
                user.update(dict(last_login=utils.utcnow(),last_login_ip=self.get_client_ip(req)))
                return Response(result)
            else:
                return Response(_("用户%s不存在或者密码错误" % username),status.HTTP_400_BAD_REQUEST)

        return Response(_("用户名或者密码不能为空"),status.HTTP_400_BAD_REQUEST)


    def logout(self,req,*args,**kwargs):
        username = self.get_params('username')
        passwd = self.get_params('password')
        if username and passwd:
            user = User.objects.first(username=username,password=passwd)
            if user:
                return Response(200)

        return Response(_("用户名或者密码不能为空"),status.HTTP_400_BAD_REQUEST)


    @transaction.autocommit
    def start(self,req,*args,**kwargs):
        username = self.get_params('username')
        passwd = self.get_params('password')
        vmid = self.get_params('id')
        if username and passwd:
            user = User.objects.first(username=username,password=passwd)
            vm = Instance.objects.get_or_none(pk=vmid)
            if user and vm and vm.user.id == user.id:
                client_start_vm.call(vm.host.host_name,vm)
                return Response(200)

        return Response(_("请输入正确的用户名密码"),status.HTTP_400_BAD_REQUEST)

